const Koa = require('koa')
const app = new Koa()
const path = require('path')
const debug = require('debug')('tpgj')
const response = require('./response')
const bodyParser = require('koa-bodyparser')
const convert = require('koa-convert')
const staticCache = require('koa-static-cache')
const compress = require('koa-compress')
const cors = require('koa2-cors')
const { port: port } = require('./config')

// 解析请求体
app.use(bodyParser())

// 跨域设置
app.use(convert(cors({
  origin: function(ctx) {
    return '*' // 本地环境
  }
})))

// 使用响应处理中间件
app.use(response)

// 中间件 设置gzip
app.use(compress({
  threshold: 2048,
  flush: require("zlib").Z_SYNC_FLUSH
}))

// 静态文件服务
app.use(convert(staticCache(path.join(__dirname, 'webroot'), {
  maxAge: 365 * 24 * 60 * 60,
  dynamic: true
})))

// 引入路由分发
const router = require('./routes')
app.use(router.routes())

// 启动程序，监听端口
app.listen(port, () => {
  debug(`listening on port ${port} for test`)
  // require('child_process').exec(`start http://localhost:${port}/index.html`);
})